package com.lw.leetcode.back.b;

/**
 * Created with IntelliJ IDEA.
 * 1254. 统计封闭岛屿的数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/18 17:25
 */
public class ClosedIsland {

    public static void main(String[] args) {
        ClosedIsland test = new ClosedIsland();

        // 1
//        int[][] arr = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};

        int[][] arr = {
                {0,0,1,1,0,1,0,0,1,0},
                {1,1,0,1,1,0,1,1,1,0},
                {1,0,1,1,1,0,0,1,1,0},
                {0,1,1,0,0,0,0,1,0,1},
                {0,0,0,0,0,0,1,1,1,0},
                {0,1,0,1,0,1,0,1,1,1},
                {1,0,1,0,1,1,0,0,0,1},
                {1,1,1,1,1,1,0,0,0,0},
                {1,1,1,0,0,1,0,1,0,1},
                {1,1,1,0,1,1,0,1,1,0}
        };

        int i = test.closedIsland(arr);
        System.out.println(i);
    }

    private int m;
    private int n;
    private int[][] grid;

    public int closedIsland(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        this.grid = grid;
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                count += (grid[i][j] == 0 && find(i, j) ? 1 : 0);
            }
        }
        return count;
    }

    private boolean find(int x, int y) {
        if (x < 0 || x == m || y < 0 || y == n) {
            return false;
        }
        if (grid[x][y] == 1) {
            return true;
        }
        grid[x][y] = 1;
        boolean b1 = find(x - 1, y);
        boolean b2 = find(x + 1, y);
        boolean b3 = find(x , y- 1);
        boolean b4 = find(x , y+ 1);
        return b1 && b2 && b3 && b4;
    }

}
